from global_names import *
from frames import empty_frame
import os
import time
from video import Video

class ContourPlayer():
	"""
	This [quick, crude, and poorly written] class takes the contour data saved by a Tracker object and reloads the contours into memory, converting them back into opencv-friendly format. It then displays the sequence of contours as a video. If the flag is set to True, it also saves these visualizations of the contours into images that can be converted into movies if desired.
	"""
	def __init__(self,contours, frame_size, save_frames = False):
		self.contours = self.list2np(contours)
		self.frame_size = frame_size
		self.save_frames = save_frames
		if save_frames:
			self.saveframes_dirname = "contour_frames_%i/" %int(time.time())
			os.system('mkdir %s' %self.saveframes_dirname)
	def play(self):
		for idx,contour in enumerate(self.contours):
			self.display_frame(contour=contour, window='contour', idx=idx)
	def display_frame(self, contour=None, window='contour_window', idx = -1):
		if contour is not None:
			contour_img = empty_frame(self.frame_size)
			cv2.drawContours( contour_img, [contour], 0, CD_COLOR, thickness=CD_THICKNESS)
			cv2.imshow(window, contour_img)
			if self.save_frames:
				frame_name = '%s%i.jpg'%(self.saveframes_dirname,idx)
				cv2.imwrite(frame_name,contour_img)
			k = cv2.waitKey(playback_mspf)
	def list2np(self,lis):
		new = []
		for con in lis:
			points = []
			for p in con:
				newp = np.array([np.int32(p[0]),np.int32(p[1])])
				nestedp = np.array([newp])
				points.append(nestedp)
			new.append(np.array(points))
		return new
		
class FramePlayer():
	def __init__(self, video_dir, save_frames = False):
		self.video = Video(video_dir)
		self.save_frames = save_frames
		if save_frames:
			self.saveframes_dirname = "frames_%i/" %int(time.time())
			os.system('mkdir %s' %self.saveframes_dirname)
	def play(self):
		for idx,frame in enumerate(self.video.frames):
			cv2.imshow('frame_window', frame.get_image())
			k = cv2.waitKey(playback_mspf)
			if self.save_frames:
				frame_name = '%s%i.jpg'%(self.saveframes_dirname,idx)
				cv2.imwrite(frame_name,frame.get_image())